/**
 * 
 */
package cn.com.xf.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import cn.com.xf.common.Constants;
import cn.com.xf.dao.TblCheckScheduleDAO;
import cn.com.xf.dao.TblCheckShiftDAO;
import cn.com.xf.dao.TblOaAuthPermissionDAO;
import cn.com.xf.dao.TblOaAuthRoleDAO;
import cn.com.xf.dao.TblOaAuthUserDAO;
import cn.com.xf.dao.TsUserDAO;
import cn.com.xf.domain.ComparatorScheduleTime;
import cn.com.xf.domain.ScheduleTime;
import cn.com.xf.domain.TblCheckSchedule;
import cn.com.xf.domain.TblCheckShift;
import cn.com.xf.domain.TblOaAuthPermission;
import cn.com.xf.domain.TblOaAuthRole;
import cn.com.xf.domain.TblOaAuthUser;
import cn.com.xf.domain.TsUser;
import cn.com.xf.service.CheckShiftService;
import cn.com.xf.web.form.LeaveForm;
import cn.com.xf.web.security.UserInfo;

/**
 * @author Administrator
 * 
 */
@Service
public class CheckShiftServiceImpl implements CheckShiftService {
	@Autowired
	private TblCheckShiftDAO tblCheckShiftDAO;
	@Autowired
	private TblCheckScheduleDAO tblCheckScheduleDAO;
	@Autowired
	private TblOaAuthRoleDAO tblOaAuthRoleDAO;
	@Autowired
	private TsUserDAO tsUserDAO;
	@Autowired
	private TblOaAuthUserDAO tblOaAuthUserDAO;
	@Autowired
	private TblOaAuthPermissionDAO tblOaAuthPermissionDAO;

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.xf.service.CheckScheduleService#selectShift()
	 */
	@Override
	public List<TblCheckShift> selectShift() {
		// TODO Auto-generated method stub
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.xf.service.CheckScheduleService#insertShift(cn.com.xf.web.form
	 * .CheckForm)
	 */
	@Override
	public Map<String, String> insertShift(LeaveForm form) throws Exception {
		TblCheckShift shift = new TblCheckShift();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Map<String, String> errMap = new HashMap<String, String>();
		String errMsg = "";
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = user.getName();
		// 1.读取数据
		String shiftName = form.getShiftName();
		if (StringUtils.isBlank(shiftName)) {
			errMsg = "班次名称未设置";
			errMap.put("errMsg", errMsg);
			return errMap;
		}
		String siteId = form.getSiteid();

		String fCheckintime = "";
		String fCheckintime_hour = form.getfCheckintime_hour();
		// 检查控制，如果第一个上班打卡时间未设置，整体设置无效
		if (StringUtils.isBlank(fCheckintime_hour)) {
			errMsg = "第一个上班签到时间未设置";
			errMap.put("errMsg", errMsg);
			return errMap;
		}
		String fCheckintime_minute = form.getfCheckintime_minute();
		if (StringUtils.isNotBlank(fCheckintime_hour) && StringUtils.isBlank(fCheckintime_minute)) {
			fCheckintime_minute = "00";
		}
		fCheckintime = fCheckintime_hour + ":" + fCheckintime_minute;

		String fCheckouttime = "";
		String fCheckouttime_hour = form.getfCheckouttime_hour();
		if (StringUtils.isBlank(fCheckouttime_hour)) {
			errMsg = "第一个下班签退时间未设置";
			errMap.put("errMsg", errMsg);
			return errMap;
		}
		String fCheckouttime_minute = form.getfCheckouttime_minute();
		if (StringUtils.isNotBlank(fCheckouttime_hour) && StringUtils.isBlank(fCheckouttime_minute)) {
			fCheckouttime_minute = "00";
		}
		fCheckouttime = fCheckouttime_hour + ":" + fCheckouttime_minute;

		if (StringUtils.isNotBlank(fCheckouttime_hour)) {
			// 检查控制，签退时间，不能大于签到时间
			Date fin = sdf.parse("2000-01-01 " + fCheckintime);
			Date fout = sdf.parse("2000-01-01 " + fCheckouttime);
			if (fin.getTime() >= fout.getTime()) {
				errMsg = "第一个上班时间应小于下班时间";
				errMap.put("errMsg", errMsg);
				return errMap;
			}
		}

		Short fAllowEarlierMinute = StringUtils.isNotEmpty(form.getfAllowEarlierMinute()) ? Short.valueOf(form
				.getfAllowEarlierMinute()) : null;
		Short fAllowLaterMinute = StringUtils.isNotEmpty(form.getfAllowLaterMinute()) ? Short.valueOf(form
				.getfAllowLaterMinute()) : null;
		Short fLaterMinute = StringUtils.isNotEmpty(form.getfLaterMinute()) ? Short.valueOf(form.getfLaterMinute())
				: null;
		Short fEarlierMinute = StringUtils.isNotEmpty(form.getfEarlierMinute()) ? Short.valueOf(form
				.getfEarlierMinute()) : null;
		String fAsLate = form.getfAsLate();
		String fAsEarly = form.getfAsEarly();
		String fWorkDay = form.getfWorkDay();
		String fCheckedDays = form.getfCheckedDays();
		if (StringUtils.isBlank(fWorkDay)) {
			// 检查控制，第一个时间段，必须设置至少一个工作日
			errMsg = "第一个班次，至少选择一天工作日";
			errMap.put("errMsg", errMsg);
			return errMap;
		}

		String sCheckintime = "";
		String sCheckintime_hour = form.getsCheckintime_hour();
		// 第二个班次，一切以上班的时间的设置为基准，若没有设置，则不考虑
		if (StringUtils.isNotBlank(sCheckintime_hour)) {
			String sCheckintime_minute = form.getsCheckintime_minute();
			if (StringUtils.isNotBlank(sCheckintime_hour) && StringUtils.isBlank(sCheckintime_minute)) {
				sCheckintime_minute = "00";
			}
			sCheckintime = sCheckintime_hour + ":" + sCheckintime_minute;
			if (StringUtils.isNotBlank(sCheckintime_hour)) {
				// 检查控制，第二个上班时间，必须小于第一个上班时间，和第一个下班时间
				Date fin = sdf.parse("2000-01-01 " + fCheckintime);
				Date sin = sdf.parse("2000-01-01 " + sCheckintime);
				Date fout = sdf.parse("2000-01-01 " + fCheckouttime);
				if (fin.getTime() >= sin.getTime()) {
					errMsg = "第一个上班时间应小于第二个上班时间";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
				if (fout.getTime() >= sin.getTime()) {
					errMsg = "第一个下班时间应小于第二个上班时间";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
			}

			String sCheckouttime = "";
			String sCheckouttime_hour = form.getsCheckouttime_hour();
			if (StringUtils.isNotBlank(sCheckintime_hour) && StringUtils.isBlank(sCheckouttime_hour)) {
				errMsg = "第二个下班签退时间未设置";
				errMap.put("errMsg", errMsg);
				return errMap;
			}
			String sCheckouttime_minute = form.getsCheckouttime_minute();
			if (StringUtils.isNotBlank(sCheckouttime_hour) && StringUtils.isBlank(sCheckouttime_minute)) {
				sCheckouttime_minute = "00";
			}
			sCheckouttime = sCheckouttime_hour + ":" + sCheckouttime_minute;

			if (StringUtils.isNotBlank(sCheckouttime_hour)) {
				// 检查控制，签退时间，不能大于签到时间
				Date sin = sdf.parse("2000-01-01 " + sCheckintime);
				Date sout = sdf.parse("2000-01-01 " + sCheckouttime);
				if (sin.getTime() >= sout.getTime()) {
					errMsg = "第二个上班时间应小于下班时间";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
			}

			Short sAllowEarlierMinute = StringUtils.isNotEmpty(form.getsAllowEarlierMinute()) ? Short.valueOf(form
					.getsAllowEarlierMinute()) : null;
			Short sAllowLaterMinute = StringUtils.isNotEmpty(form.getsAllowLaterMinute()) ? Short.valueOf(form
					.getsAllowLaterMinute()) : null;
			Short sLaterMinute = StringUtils.isNotEmpty(form.getsLaterMinute()) ? Short.valueOf(form.getsLaterMinute())
					: null;
			Short sEarlierMinute = StringUtils.isNotEmpty(form.getsEarlierMinute()) ? Short.valueOf(form
					.getsEarlierMinute()) : null;
			String sAsLate = form.getsAsLate();
			String sAsEarly = form.getsAsEarly();
			String sWorkDay = form.getsWorkDay();
			String sCheckedDays = form.getsCheckedDays();
			if (StringUtils.isBlank(sWorkDay)) {
				// 检查控制，第一个时间段，必须设置至少一个工作日
				errMsg = "第二个班次，至少选择一天工作日";
				errMap.put("errMsg", errMsg);
				return errMap;
			}

			shift.setsCheckintime(sCheckintime);
			shift.setsCheckouttime(sCheckouttime);

			shift.setsAllowEarlierMinute(sAllowEarlierMinute);
			shift.setsAllowLaterMinute(sAllowLaterMinute);
			shift.setsLaterMinute(sLaterMinute);
			shift.setsEarlierMinute(sEarlierMinute);
			shift.setsAsLate(sAsLate);

			shift.setsAsEarly(sAsEarly);
			shift.setsWorkDay(sWorkDay);
			shift.setsCheckedDays(sCheckedDays);

			// ----------------------------------------------------------
			// 第三个时间段的设置，必须建立在已经设置了第二个时间段的基础之上
			String tCheckintime = "";
			String tCheckintime_hour = form.gettCheckintime_hour();
			if (StringUtils.isNotBlank(tCheckintime_hour)) {
				String tCheckintime_minute = form.gettCheckintime_minute();
				if (StringUtils.isBlank(tCheckintime_minute)) {
					tCheckintime_minute = "00";
				}
				tCheckintime = tCheckintime_hour + ":" + tCheckintime_minute;
				if (StringUtils.isNotBlank(tCheckintime_hour)) {
					// 检查控制，第三个上班时间，必须大于第二个上班时间，和第二个下班时间
					Date sin = sdf.parse("2000-01-01 " + sCheckintime);
					Date tin = sdf.parse("2000-01-01 " + tCheckintime);
					Date sout = sdf.parse("2000-01-01 " + sCheckouttime);
					if (sin.getTime() >= tin.getTime()) {
						errMsg = "第二个上班时间应小于第三个上班时间";
						errMap.put("errMsg", errMsg);
						return errMap;
					}
					if (sout.getTime() >= tin.getTime()) {
						errMsg = "第二个下班时间应小于第三个上班时间";
						errMap.put("errMsg", errMsg);
						return errMap;
					}
				}

				String tCheckouttime = "";
				String tCheckouttime_hour = form.gettCheckouttime_hour();
				if (StringUtils.isBlank(tCheckouttime_hour)) {
					errMsg = "第三个下班签退时间未设置";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
				String tCheckouttime_minute = form.gettCheckouttime_minute();
				if (StringUtils.isNotBlank(tCheckouttime_hour) && StringUtils.isBlank(tCheckouttime_minute)) {
					tCheckouttime_minute = "00";
				}
				tCheckouttime = tCheckouttime_hour + ":" + tCheckouttime_minute;
				if (StringUtils.isNotBlank(tCheckouttime_hour)) {
					// 检查控制，签退时间，不能大于签到时间
					Date tin = sdf.parse("2000-01-01 " + tCheckintime);
					Date tout = sdf.parse("2000-01-01 " + tCheckouttime);
					if (tin.getTime() >= tout.getTime()) {
						errMsg = "第三个上班时间应小于下班时间";
						errMap.put("errMsg", errMsg);
						return errMap;
					}
				}

				Short tAllowEarlierMinute = StringUtils.isNotEmpty(form.gettAllowEarlierMinute()) ? Short.valueOf(form
						.gettAllowEarlierMinute()) : null;
				Short tAllowLaterMinute = StringUtils.isNotEmpty(form.gettAllowLaterMinute()) ? Short.valueOf(form
						.gettAllowLaterMinute()) : null;
				Short tLaterMinute = StringUtils.isNotEmpty(form.gettLaterMinute()) ? Short.valueOf(form
						.gettLaterMinute()) : null;
				Short tEarlierMinute = StringUtils.isNotEmpty(form.gettEarlierMinute()) ? Short.valueOf(form
						.gettEarlierMinute()) : null;
				String tAsLate = form.gettAsLate();
				String tAsEarly = form.gettAsEarly();

				String tWorkDay = form.gettWorkDay();
				String tCheckedDays = form.gettCheckedDays();
				if (StringUtils.isBlank(tWorkDay)) {
					// 检查控制，第一个时间段，必须设置至少一个工作日
					errMsg = "第三个班次，至少选择一天工作日";
					errMap.put("errMsg", errMsg);
					return errMap;
				}

				shift.settWorkDay(tWorkDay);
				shift.settCheckedDays(tCheckedDays);

				shift.settCheckintime(tCheckintime);
				shift.settCheckouttime(tCheckouttime);
				shift.settAllowEarlierMinute(tAllowEarlierMinute);
				shift.settAllowLaterMinute(tAllowLaterMinute);
				shift.settLaterMinute(tLaterMinute);

				shift.settEarlierMinute(tEarlierMinute);
				shift.settAsLate(tAsLate);
				shift.settAsEarly(tAsEarly);
			}
		}

		// 2.存储
		shift.setShiftName(shiftName);
		shift.setSiteid(siteId);
		shift.setAddTime(new Date());
		shift.setAddUser(username);
		shift.setfCheckintime(fCheckintime);
		shift.setfCheckouttime(fCheckouttime);
		shift.setfAllowEarlierMinute(fAllowEarlierMinute);
		shift.setfAllowLaterMinute(fAllowLaterMinute);
		shift.setfLaterMinute(fLaterMinute);

		shift.setfEarlierMinute(fEarlierMinute);
		shift.setfAsLate(fAsLate);
		shift.setfAsEarly(fAsEarly);
		shift.setfWorkDay(fWorkDay);
		shift.setfCheckedDays(fCheckedDays);

		tblCheckShiftDAO.insertSelective(shift);
		return errMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.com.xf.service.CheckScheduleService#updateShift(cn.com.xf.web.form
	 * .CheckForm)
	 */
	@Override
	public Map<String, String> updateShift(LeaveForm form, String realId) throws Exception {
		TblCheckShift shift = new TblCheckShift();
		shift.setId(Long.valueOf(realId));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Map<String, String> errMap = new HashMap<String, String>();
		String errMsg = "";
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = user.getName();
		// 1.读取数据
		String shiftName = form.getShiftName();
		if (StringUtils.isBlank(shiftName)) {
			errMsg = "班次名称未设置";
			errMap.put("errMsg", errMsg);
			return errMap;
		}
		String siteId = form.getSiteid();

		String fCheckintime = "";
		String fCheckintime_hour = form.getfCheckintime_hour();
		// 检查控制，如果第一个上班打卡时间未设置，整体设置无效
		if (StringUtils.isBlank(fCheckintime_hour)) {
			errMsg = "第一个上班签到时间未设置";
			errMap.put("errMsg", errMsg);
			return errMap;
		}
		String fCheckintime_minute = form.getfCheckintime_minute();
		if (StringUtils.isNotBlank(fCheckintime_hour) && StringUtils.isBlank(fCheckintime_minute)) {
			fCheckintime_minute = "00";
		}
		fCheckintime = fCheckintime_hour + ":" + fCheckintime_minute;

		String fCheckouttime = "";
		String fCheckouttime_hour = form.getfCheckouttime_hour();
		if (StringUtils.isBlank(fCheckouttime_hour)) {
			errMsg = "第一个下班签退时间未设置";
			errMap.put("errMsg", errMsg);
			return errMap;
		}
		String fCheckouttime_minute = form.getfCheckouttime_minute();
		if (StringUtils.isNotBlank(fCheckouttime_hour) && StringUtils.isBlank(fCheckouttime_minute)) {
			fCheckouttime_minute = "00";
		}
		fCheckouttime = fCheckouttime_hour + ":" + fCheckouttime_minute;

		if (StringUtils.isNotBlank(fCheckouttime_hour)) {
			// 检查控制，签退时间，不能大于签到时间
			Date fin = sdf.parse("2000-01-01 " + fCheckintime);
			Date fout = sdf.parse("2000-01-01 " + fCheckouttime);
			if (fin.getTime() >= fout.getTime()) {
				errMsg = "第一个上班时间应小于下班时间";
				errMap.put("errMsg", errMsg);
				return errMap;
			}
		}

		Short fAllowEarlierMinute = StringUtils.isNotEmpty(form.getfAllowEarlierMinute()) ? Short.valueOf(form
				.getfAllowEarlierMinute()) : null;
		Short fAllowLaterMinute = StringUtils.isNotEmpty(form.getfAllowLaterMinute()) ? Short.valueOf(form
				.getfAllowLaterMinute()) : null;
		Short fLaterMinute = StringUtils.isNotEmpty(form.getfLaterMinute()) ? Short.valueOf(form.getfLaterMinute())
				: null;
		Short fEarlierMinute = StringUtils.isNotEmpty(form.getfEarlierMinute()) ? Short.valueOf(form
				.getfEarlierMinute()) : null;
		String fAsLate = form.getfAsLate();
		String fAsEarly = form.getfAsEarly();
		String fWorkDay = form.getfWorkDay();
		String fCheckedDays = form.getfCheckedDays();
		if (StringUtils.isBlank(fWorkDay)) {
			// 检查控制，第一个时间段，必须设置至少一个工作日
			errMsg = "第一个班次，至少选择一天工作日";
			errMap.put("errMsg", errMsg);
			return errMap;
		}

		String sCheckintime = "";
		String sCheckintime_hour = form.getsCheckintime_hour();
		// 第二个班次，一切以上班的时间的设置为基准，若没有设置，则不考虑
		if (StringUtils.isNotBlank(sCheckintime_hour)) {
			String sCheckintime_minute = form.getsCheckintime_minute();
			if (StringUtils.isNotBlank(sCheckintime_hour) && StringUtils.isBlank(sCheckintime_minute)) {
				sCheckintime_minute = "00";
			}
			sCheckintime = sCheckintime_hour + ":" + sCheckintime_minute;
			if (StringUtils.isNotBlank(sCheckintime_hour)) {
				// 检查控制，第二个上班时间，必须小于第一个上班时间，和第一个下班时间
				Date fin = sdf.parse("2000-01-01 " + fCheckintime);
				Date sin = sdf.parse("2000-01-01 " + sCheckintime);
				Date fout = sdf.parse("2000-01-01 " + fCheckouttime);
				if (fin.getTime() >= sin.getTime()) {
					errMsg = "第一个上班时间应小于第二个上班时间";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
				if (fout.getTime() >= sin.getTime()) {
					errMsg = "第一个下班时间应小于第二个上班时间";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
			}

			String sCheckouttime = "";
			String sCheckouttime_hour = form.getsCheckouttime_hour();
			if (StringUtils.isNotBlank(sCheckintime_hour) && StringUtils.isBlank(sCheckouttime_hour)) {
				errMsg = "第二个下班签退时间未设置";
				errMap.put("errMsg", errMsg);
				return errMap;
			}
			String sCheckouttime_minute = form.getsCheckouttime_minute();
			if (StringUtils.isNotBlank(sCheckouttime_hour) && StringUtils.isBlank(sCheckouttime_minute)) {
				sCheckouttime_minute = "00";
			}
			sCheckouttime = sCheckouttime_hour + ":" + sCheckouttime_minute;

			if (StringUtils.isNotBlank(sCheckouttime_hour)) {
				// 检查控制，签退时间，不能大于签到时间
				Date sin = sdf.parse("2000-01-01 " + sCheckintime);
				Date sout = sdf.parse("2000-01-01 " + sCheckouttime);
				if (sin.getTime() >= sout.getTime()) {
					errMsg = "第二个上班时间应小于下班时间";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
			}

			Short sAllowEarlierMinute = StringUtils.isNotEmpty(form.getsAllowEarlierMinute()) ? Short.valueOf(form
					.getsAllowEarlierMinute()) : null;
			Short sAllowLaterMinute = StringUtils.isNotEmpty(form.getsAllowLaterMinute()) ? Short.valueOf(form
					.getsAllowLaterMinute()) : null;
			Short sLaterMinute = StringUtils.isNotEmpty(form.getsLaterMinute()) ? Short.valueOf(form.getsLaterMinute())
					: null;
			Short sEarlierMinute = StringUtils.isNotEmpty(form.getsEarlierMinute()) ? Short.valueOf(form
					.getsEarlierMinute()) : null;
			String sAsLate = form.getsAsLate();
			String sAsEarly = form.getsAsEarly();
			String sWorkDay = form.getsWorkDay();
			String sCheckedDays = form.getsCheckedDays();
			if (StringUtils.isBlank(sWorkDay)) {
				// 检查控制，第一个时间段，必须设置至少一个工作日
				errMsg = "第二个班次，至少选择一天工作日";
				errMap.put("errMsg", errMsg);
				return errMap;
			}

			shift.setsCheckintime(sCheckintime);
			shift.setsCheckouttime(sCheckouttime);

			shift.setsAllowEarlierMinute(sAllowEarlierMinute);
			shift.setsAllowLaterMinute(sAllowLaterMinute);
			shift.setsLaterMinute(sLaterMinute);
			shift.setsEarlierMinute(sEarlierMinute);
			shift.setsAsLate(sAsLate);

			shift.setsAsEarly(sAsEarly);
			shift.setsWorkDay(sWorkDay);
			shift.setsCheckedDays(sCheckedDays);

			// ----------------------------------------------------------
			// 第三个时间段的设置，必须建立在已经设置了第二个时间段的基础之上
			String tCheckintime = "";
			String tCheckintime_hour = form.gettCheckintime_hour();
			if (StringUtils.isNotBlank(tCheckintime_hour)) {
				String tCheckintime_minute = form.gettCheckintime_minute();
				if (StringUtils.isBlank(tCheckintime_minute)) {
					tCheckintime_minute = "00";
				}
				tCheckintime = tCheckintime_hour + ":" + tCheckintime_minute;
				if (StringUtils.isNotBlank(tCheckintime_hour)) {
					// 检查控制，第三个上班时间，必须大于第二个上班时间，和第二个下班时间
					Date sin = sdf.parse("2000-01-01 " + sCheckintime);
					Date tin = sdf.parse("2000-01-01 " + tCheckintime);
					Date sout = sdf.parse("2000-01-01 " + sCheckouttime);
					if (sin.getTime() >= tin.getTime()) {
						errMsg = "第二个上班时间应小于第三个上班时间";
						errMap.put("errMsg", errMsg);
						return errMap;
					}
					if (sout.getTime() >= tin.getTime()) {
						errMsg = "第二个下班时间应小于第三个上班时间";
						errMap.put("errMsg", errMsg);
						return errMap;
					}
				}

				String tCheckouttime = "";
				String tCheckouttime_hour = form.gettCheckouttime_hour();
				if (StringUtils.isBlank(tCheckouttime_hour)) {
					errMsg = "第三个下班签退时间未设置";
					errMap.put("errMsg", errMsg);
					return errMap;
				}
				String tCheckouttime_minute = form.gettCheckouttime_minute();
				if (StringUtils.isNotBlank(tCheckouttime_hour) && StringUtils.isBlank(tCheckouttime_minute)) {
					tCheckouttime_minute = "00";
				}
				tCheckouttime = tCheckouttime_hour + ":" + tCheckouttime_minute;
				if (StringUtils.isNotBlank(tCheckouttime_hour)) {
					// 检查控制，签退时间，不能大于签到时间
					Date tin = sdf.parse("2000-01-01 " + tCheckintime);
					Date tout = sdf.parse("2000-01-01 " + tCheckouttime);
					if (tin.getTime() >= tout.getTime()) {
						errMsg = "第三个上班时间应小于下班时间";
						errMap.put("errMsg", errMsg);
						return errMap;
					}
				}

				Short tAllowEarlierMinute = StringUtils.isNotEmpty(form.gettAllowEarlierMinute()) ? Short.valueOf(form
						.gettAllowEarlierMinute()) : null;
				Short tAllowLaterMinute = StringUtils.isNotEmpty(form.gettAllowLaterMinute()) ? Short.valueOf(form
						.gettAllowLaterMinute()) : null;
				Short tLaterMinute = StringUtils.isNotEmpty(form.gettLaterMinute()) ? Short.valueOf(form
						.gettLaterMinute()) : null;
				Short tEarlierMinute = StringUtils.isNotEmpty(form.gettEarlierMinute()) ? Short.valueOf(form
						.gettEarlierMinute()) : null;
				String tAsLate = form.gettAsLate();
				String tAsEarly = form.gettAsEarly();

				String tWorkDay = form.gettWorkDay();
				String tCheckedDays = form.gettCheckedDays();
				if (StringUtils.isBlank(tWorkDay)) {
					// 检查控制，第一个时间段，必须设置至少一个工作日
					errMsg = "第三个班次，至少选择一天工作日";
					errMap.put("errMsg", errMsg);
					return errMap;
				}

				shift.settWorkDay(tWorkDay);
				shift.settCheckedDays(tCheckedDays);

				shift.settCheckintime(tCheckintime);
				shift.settCheckouttime(tCheckouttime);
				shift.settAllowEarlierMinute(tAllowEarlierMinute);
				shift.settAllowLaterMinute(tAllowLaterMinute);
				shift.settLaterMinute(tLaterMinute);

				shift.settEarlierMinute(tEarlierMinute);
				shift.settAsLate(tAsLate);
				shift.settAsEarly(tAsEarly);
			}
		}

		// 2.存储
		shift.setShiftName(shiftName);
		shift.setSiteid(siteId);
		shift.setAddTime(new Date());
		shift.setAddUser(username);
		shift.setfCheckintime(fCheckintime);
		shift.setfCheckouttime(fCheckouttime);
		shift.setfAllowEarlierMinute(fAllowEarlierMinute);
		shift.setfAllowLaterMinute(fAllowLaterMinute);
		shift.setfLaterMinute(fLaterMinute);

		shift.setfEarlierMinute(fEarlierMinute);
		shift.setfAsLate(fAsLate);
		shift.setfAsEarly(fAsEarly);
		shift.setfWorkDay(fWorkDay);
		shift.setfCheckedDays(fCheckedDays);

		tblCheckShiftDAO.updateByPrimaryKeySelective(shift);
		return errMap;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.com.xf.service.CheckScheduleService#deleteShift(java.lang.String)
	 */
	@Override
	public int deleteShift(String id) {
		int result = 1;
		tblCheckShiftDAO.deleteByPrimaryKey(Long.valueOf(id));
		return result;
	}

	@Override
	public List<TblCheckShift> selectShift(int begin, int pageSize, String siteid, String deptid) {
		return tblCheckShiftDAO.select(begin, pageSize, siteid, deptid);
	}

	@Override
	public int selectShiftCount(String siteid, String deptid) {
		return tblCheckShiftDAO.selectCount(siteid, deptid);
	}

	@Override
	public TblCheckShift selectShiftById(String id) {
		return tblCheckShiftDAO.selectShiftById(Long.valueOf(id));
	}

	@Override
	public List<TblCheckSchedule> selectSchedule() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int insertSchedule(LeaveForm form) throws Exception {
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = user.getName();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 1.读取数据
		String siteId = form.getSiteid();
		String userId = form.getUserid();
		String isCheck = form.getIsCheck();
		String isHoliday = form.getIsHoliday();
		String isOvertime = form.getIsOvertime();
		int count = 0;
		if (StringUtils.isNotBlank(form.getShiftid()) && StringUtils.isNotBlank(form.getStartDate())
				&& StringUtils.isNotBlank(form.getEndDate()) && StringUtils.isNotBlank(userId)) {
			String[] users = userId.split(",");
			for (String userid : users) {
				List<TblCheckSchedule> schedules = tblCheckScheduleDAO.selectScheduleByUserid(userid);
				Date startdate = sdf.parse(form.getStartDate());
				Date enddate = sdf.parse(form.getEndDate());
				boolean isLegal = true;
				for (TblCheckSchedule s : schedules) {
					if (startdate.compareTo(s.getStartdate()) >= 0 && startdate.compareTo(s.getEnddate()) <= 0) {
						isLegal = false;
						break;
					}
					if (enddate.compareTo(s.getStartdate()) >= 0 && enddate.compareTo(s.getEnddate()) <= 0) {
						isLegal = false;
						break;
					}
				}
				if (isLegal) {
					TblCheckSchedule schedule = new TblCheckSchedule();
					schedule.setSiteid(siteId);
					schedule.setUserid(userid);
					schedule.setShiftid(Long.valueOf(form.getShiftid()));
					schedule.setStartdate(startdate);
					schedule.setEnddate(enddate);
					schedule.setIsCheck(isCheck);
					schedule.setIsHodliday(isHoliday);
					schedule.setIsOvertime(isOvertime);
					schedule.setAddtime(new Date());
					schedule.setAdduser(username);
					tblCheckScheduleDAO.insertSelective(schedule);
					count++;
				}

			}
		}
		// if (StringUtils.isNotBlank(form.getShiftid2()) &&
		// StringUtils.isNotBlank(form.getStartDate2())
		// && StringUtils.isNotBlank(form.getEndDate2())) {
		// TblCheckSchedule schedule = new TblCheckSchedule();
		// schedule.setSiteid(siteId);
		// schedule.setUserid(userId);
		// schedule.setShiftid(Long.valueOf(form.getShiftid2()));
		// schedule.setStartdate(sdf.parse(form.getStartDate2()));
		// schedule.setEnddate(sdf.parse(form.getEndDate2()));
		//
		// schedule.setIsCheck(isCheck);
		// schedule.setIsHodliday(isHoliday);
		// schedule.setIsOvertime(isOvertime);
		// schedule.setAddtime(new Date());
		// schedule.setAdduser(username);
		// tblCheckScheduleDAO.insertSelective(schedule);
		// } else {
		// return 1;
		// }
		// if (StringUtils.isNotBlank(form.getShiftid3()) &&
		// StringUtils.isNotBlank(form.getStartDate3())
		// && StringUtils.isNotBlank(form.getEndDate3())) {
		// TblCheckSchedule schedule = new TblCheckSchedule();
		// schedule.setSiteid(siteId);
		// schedule.setUserid(userId);
		// schedule.setShiftid(Long.valueOf(form.getShiftid3()));
		// schedule.setStartdate(sdf.parse(form.getStartDate3()));
		// schedule.setEnddate(sdf.parse(form.getEndDate3()));
		//
		// schedule.setIsCheck(isCheck);
		// schedule.setIsHodliday(isHoliday);
		// schedule.setIsOvertime(isOvertime);
		// schedule.setAddtime(new Date());
		// schedule.setAdduser(username);
		// tblCheckScheduleDAO.insertSelective(schedule);
		// } else {
		// return 1;
		// }
		// if (StringUtils.isNotBlank(form.getShiftid4()) &&
		// StringUtils.isNotBlank(form.getStartDate4())
		// && StringUtils.isNotBlank(form.getEndDate4())) {
		// TblCheckSchedule schedule = new TblCheckSchedule();
		// schedule.setSiteid(siteId);
		// schedule.setUserid(userId);
		// schedule.setShiftid(Long.valueOf(form.getShiftid4()));
		// schedule.setStartdate(sdf.parse(form.getStartDate4()));
		// schedule.setEnddate(sdf.parse(form.getEndDate4()));
		//
		// schedule.setIsCheck(isCheck);
		// schedule.setIsHodliday(isHoliday);
		// schedule.setIsOvertime(isOvertime);
		// schedule.setAddtime(new Date());
		// schedule.setAdduser(username);
		// tblCheckScheduleDAO.insertSelective(schedule);
		// } else {
		// return 1;
		// }
		// if (StringUtils.isNotBlank(form.getShiftid5()) &&
		// StringUtils.isNotBlank(form.getStartDate5())
		// && StringUtils.isNotBlank(form.getEndDate5())) {
		// TblCheckSchedule schedule = new TblCheckSchedule();
		// schedule.setSiteid(siteId);
		// schedule.setUserid(userId);
		// schedule.setShiftid(Long.valueOf(form.getShiftid5()));
		// schedule.setStartdate(sdf.parse(form.getStartDate5()));
		// schedule.setEnddate(sdf.parse(form.getEndDate5()));
		//
		// schedule.setIsCheck(isCheck);
		// schedule.setIsHodliday(isHoliday);
		// schedule.setIsOvertime(isOvertime);
		// schedule.setAddtime(new Date());
		// schedule.setAdduser(username);
		// tblCheckScheduleDAO.insertSelective(schedule);
		// } else {
		// return 1;
		// }

		return count;
	}

	@Override
	public int updateSchedule(LeaveForm form, String realId) throws Exception {
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username = user.getName();
		// 1.读取数据
		String siteId = form.getSiteid();
		String userId = form.getUserid();
		String shiftId = form.getShiftid();
		String startdate = form.getStartDate();
		String enddate = form.getEndDate();

		String workDays = form.getWorkDays();
		String isCheck = form.getIsCheck();
		String isHoliday = form.getIsHoliday();
		String isOvertime = form.getIsOvertime();

		// 2.存储
		TblCheckSchedule schedule = new TblCheckSchedule();
		schedule.setId(Long.valueOf(realId));
		schedule.setSiteid(siteId);
		schedule.setUserid(userId);
		schedule.setShiftid(Long.valueOf(shiftId));

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		schedule.setStartdate(sdf.parse(startdate));
		schedule.setEnddate(sdf.parse(enddate));

		schedule.setIsCheck(isCheck);
		schedule.setIsHodliday(isHoliday);
		schedule.setIsOvertime(isOvertime);
		schedule.setWorkDays(workDays);

		schedule.setUpdatetime(new Date());
		schedule.setUpdateuser(username);
		tblCheckScheduleDAO.updateByPrimaryKeySelective(schedule);
		return 1;
	}

	@Override
	public int deleteSchedule(String id) {
		int result = 1;
		tblCheckScheduleDAO.deleteByPrimaryKey(Long.valueOf(id));
		return result;

	}

	@Override
	public List<TblCheckSchedule> selectSchedule(int begin, int pageSize, String siteid, String userid, String deptid) {
		List<TblCheckSchedule> list = tblCheckScheduleDAO.select(begin, pageSize, siteid, userid, deptid);
		return list;
	}

	@Override
	public int selectScheduleCount(String siteid, String userid, String deptid) {
		return tblCheckScheduleDAO.selectCount(siteid, userid, deptid);
	}

	@Override
	public TblCheckSchedule selectScheduleById(String id) {
		return tblCheckScheduleDAO.selectScheduleById(Long.valueOf(id));
	}

	@Override
	public List<TblCheckShift> selectShiftBySiteId(String siteId) {
		return tblCheckShiftDAO.selectShiftBySiteId(siteId);
	}

	@Override
	public List<TsUser> selectUser(int begin, int pageSize, String siteid, String deptid, String userid, String username) {

		// 1.获取账号的基本信息
		List<TsUser> list = tsUserDAO.selectUser4Check(begin, pageSize, siteid, deptid, userid, username);

		List<String> userNameList = new ArrayList<String>();
		if (!CollectionUtils.isEmpty(list)) {
			for (TsUser user : list) {
				userNameList.add(user.getUserid());
				user.setRoleDescs("");
				if (null != user.getEnabled()) {
					if ((user.getEnabled() + "").equals("0")) {
						user.setEnableHanzi(Constants.TS_USER_ENABLED_NO);
					} else if ((user.getEnabled() + "").equalsIgnoreCase("1")) {
						user.setEnableHanzi(Constants.TS_USER_ENABLED_YES);
					}
				}
			}
		}

		// 2.获取账户的角色
		List<TblOaAuthUser> roleList = tblOaAuthUserDAO.selectRoleByUserNames(userNameList);
		if (!CollectionUtils.isEmpty(list) && !CollectionUtils.isEmpty(roleList)) {
			for (TsUser user : list) {
				String roleDescs = "";
				for (TblOaAuthUser roleUser : roleList) {
					if (user.getUserid().equalsIgnoreCase(roleUser.getUsername())) {
						if (StringUtils.isNotBlank(roleUser.getRoleDesc())) {
							roleDescs = roleDescs + "," + roleUser.getRoleDesc();
						}
					}
				}
				roleDescs = roleDescs.replaceFirst(",", "");
				user.setRoleDescs(roleDescs);
			}
		}
		return list;

	}

	@Override
	public int selectUserCount(String siteid, String deptid, String userid, String username) {
		return tsUserDAO.selectCount4Check(siteid, deptid, userid, username);
	}

	@Override
	public List<TblOaAuthRole> selectTblOaAuthRole(int begin, int pageSize, String siteid, String rolename) {

		// 1.获取角色列表
		List<TblOaAuthRole> roleList = tblOaAuthRoleDAO.selectRoleListByQuery4Check(siteid, rolename, begin, pageSize);

		// 2.获取权限
		ArrayList<String> roleIds = new ArrayList<String>();
		for (TblOaAuthRole role : roleList) {
			roleIds.add(role.getRoleId() + "");
		}
		List<TblOaAuthPermission> permissionList = tblOaAuthPermissionDAO.selectByRoleIds(roleIds);

		// 3.合并权限数据到角色列表
		for (TblOaAuthRole role : roleList) {
			String permissionNames = "";
			for (TblOaAuthPermission p : permissionList) {
				if ((role.getRoleId() + "").equalsIgnoreCase((p.getRoleId() + ""))) {
					permissionNames = permissionNames + "," + p.getPermissionName();
				}
			}
			permissionNames = permissionNames.replaceFirst(",", "");
			role.setPermissionNames(permissionNames);
		}
		return roleList;
	}

	@Override
	public int selectTblOaAuthRoleCount(String siteid, String rolename) {
		return tblOaAuthRoleDAO.selectRoleListByQueryCount4Check(siteid, rolename);
	}

	@Override
	public Map<String, String> selectUserSchedule(String userid, String scheduleid) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = sdf.parse("2100-01-01");
		Date endDate = sdf.parse("2000-01-01");
		// 1.查询排版列表
		TblCheckSchedule schedule = tblCheckScheduleDAO.selectScheduleById(Long.parseLong(scheduleid));
		Date sd = schedule.getStartdate();
		Date ed = schedule.getEnddate();
		if (startDate.getTime() > sd.getTime()) {
			startDate = sd;
		}
		if (endDate.getTime() < ed.getTime()) {
			endDate = ed;
		}
		List<TblCheckSchedule> scheduleList = tblCheckScheduleDAO.selectScheduleByUserid(userid);
		// if (!CollectionUtils.isEmpty(scheduleList)) {
		// for (TblCheckSchedule schedule : scheduleList) {
		// Date sd = schedule.getStartdate();
		// Date ed = schedule.getEnddate();
		// if (startDate.getTime() > sd.getTime()) {
		// startDate = sd;
		// }
		// if (endDate.getTime() < ed.getTime()) {
		// endDate = ed;
		// }
		// }
		// } else {
		// return null;
		// }

		// 2.查询班次
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		// for (TblCheckSchedule schedule : scheduleList) {
		TblCheckShift shift = tblCheckShiftDAO.selectByPrimaryKey(Long.valueOf(schedule.getShiftid()));
		// 1.获取时间段
		Map<String, String> map = new HashMap<String, String>();
		String schedule1 = "";
		String schedule2 = "";
		String schedule3 = "";
		String schedule4 = "";
		String schedule5 = "";
		String schedule6 = "";
		String schedule0 = "";

		String fDuring = "";
		if (StringUtils.isNotBlank(shift.getfCheckintime()) && StringUtils.isNotBlank(shift.getfCheckouttime())) {
			fDuring = shift.getfCheckintime() + "-" + shift.getfCheckouttime() + ";";
		}
		String sDuring = "";
		if (StringUtils.isNotBlank(shift.getsCheckintime()) && StringUtils.isNotBlank(shift.getsCheckouttime())) {
			sDuring = shift.getsCheckintime() + "-" + shift.getsCheckouttime() + ";";
		}
		String tDuring = "";
		if (StringUtils.isNotBlank(shift.gettCheckintime()) && StringUtils.isNotBlank(shift.gettCheckouttime())) {
			tDuring = shift.gettCheckintime() + "-" + shift.gettCheckouttime() + ";";
		}

		if (StringUtils.isNotBlank(shift.getfWorkDay())) {
			String fWorkDays = shift.getfWorkDay();
			if (fWorkDays.contains("1")) {
				schedule1 = schedule1 + fDuring;
			}
			if (fWorkDays.contains("2")) {
				schedule2 = schedule2 + fDuring;
			}
			if (fWorkDays.contains("3")) {
				schedule3 = schedule3 + fDuring;
			}
			if (fWorkDays.contains("4")) {
				schedule4 = schedule4 + fDuring;
			}
			if (fWorkDays.contains("5")) {
				schedule5 = schedule5 + fDuring;
			}
			if (fWorkDays.contains("6")) {
				schedule6 = schedule6 + fDuring;
			}
			if (fWorkDays.contains("0")) {
				schedule0 = schedule0 + fDuring;
			}
		}

		if (StringUtils.isNotBlank(shift.getsWorkDay())) {
			String sWorkDays = shift.getsWorkDay();
			if (sWorkDays.contains("1")) {
				schedule1 = schedule1 + sDuring;
			}
			if (sWorkDays.contains("2")) {
				schedule2 = schedule2 + sDuring;
			}
			if (sWorkDays.contains("3")) {
				schedule3 = schedule3 + sDuring;
			}
			if (sWorkDays.contains("4")) {
				schedule4 = schedule4 + sDuring;
			}
			if (sWorkDays.contains("5")) {
				schedule5 = schedule5 + sDuring;
			}
			if (sWorkDays.contains("6")) {
				schedule6 = schedule6 + sDuring;
			}
			if (sWorkDays.contains("0")) {
				schedule0 = schedule0 + sDuring;
			}
		}

		if (StringUtils.isNotBlank(shift.gettWorkDay())) {
			String tWorkDays = shift.gettWorkDay();
			if (tWorkDays.contains("1")) {
				schedule1 = schedule1 + tDuring;
			}
			if (tWorkDays.contains("2")) {
				schedule2 = schedule2 + tDuring;
			}
			if (tWorkDays.contains("3")) {
				schedule3 = schedule3 + tDuring;
			}
			if (tWorkDays.contains("4")) {
				schedule4 = schedule4 + tDuring;
			}
			if (tWorkDays.contains("5")) {
				schedule5 = schedule5 + tDuring;
			}
			if (tWorkDays.contains("6")) {
				schedule6 = schedule6 + tDuring;
			}
			if (tWorkDays.contains("0")) {
				schedule0 = schedule0 + tDuring;
			}
		}
		map.put("1", schedule1);
		map.put("2", schedule2);
		map.put("3", schedule3);
		map.put("4", schedule4);
		map.put("5", schedule5);
		map.put("6", schedule6);
		map.put("0", schedule0);
		list.add(map);
		// }

		// 合并时间段
		Map<String, String> returnMap = new HashMap<String, String>();
		String scheduled1 = "";
		String scheduled2 = "";
		String scheduled3 = "";
		String scheduled4 = "";
		String scheduled5 = "";
		String scheduled6 = "";
		String scheduled0 = "";
		if (!CollectionUtils.isEmpty(list)) {
			for (Map<String, String> m : list) {
				if (StringUtils.isNotBlank(m.get("1"))) {
					scheduled1 = scheduled1 + m.get("1") + ";";
				}
				if (StringUtils.isNotBlank(m.get("2"))) {
					scheduled2 = scheduled2 + m.get("2") + ";";
				}
				if (StringUtils.isNotBlank(m.get("3"))) {
					scheduled3 = scheduled3 + m.get("3") + ";";
				}
				if (StringUtils.isNotBlank(m.get("4"))) {
					scheduled4 = scheduled4 + m.get("4") + ";";
				}
				if (StringUtils.isNotBlank(m.get("5"))) {
					scheduled5 = scheduled5 + m.get("5") + ";";
				}
				if (StringUtils.isNotBlank(m.get("6"))) {
					scheduled6 = scheduled6 + m.get("6") + ";";
				}
				if (StringUtils.isNotBlank(m.get("0"))) {
					scheduled0 = scheduled0 + m.get("0") + ";";
				}
			}
		}
		returnMap.put("1", orderSchedule(scheduled1));
		returnMap.put("2", orderSchedule(scheduled2));
		returnMap.put("3", orderSchedule(scheduled3));
		returnMap.put("4", orderSchedule(scheduled4));
		returnMap.put("5", orderSchedule(scheduled5));
		returnMap.put("6", orderSchedule(scheduled6));
		returnMap.put("0", orderSchedule(scheduled0));
		returnMap.put("startDate", DateFormatUtils.format(startDate, "yyyy-MM-dd"));
		returnMap.put("endDate", DateFormatUtils.format(endDate, "yyyy-MM-dd"));
		return returnMap;
	}

	@SuppressWarnings("unchecked")
	private String orderSchedule(String schedule) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<ScheduleTime> list = new ArrayList<ScheduleTime>();
		if (StringUtils.isNotBlank(schedule)) {
			if (schedule.split(";").length > 0) {
				String arr[] = schedule.split(";");
				for (String s : arr) {
					if (StringUtils.isNotBlank(s)) {
						String calStr = "2000-01-01 " + s.split("-")[0];
						Date date = sdf.parse(calStr);
						Long t = date.getTime();
						ScheduleTime st = new ScheduleTime();
						st.setS(s);
						st.setT(t);
						list.add(st);
					}
				}
			}
		}
		String returnS = "";
		if (!CollectionUtils.isEmpty(list)) {
			ComparatorScheduleTime comparator = new ComparatorScheduleTime();
			Collections.sort(list, comparator);
			for (ScheduleTime st : list) {
				returnS = returnS + st.getS() + ";";
			}
			return returnS;
		}
		return "";
	}
}
